<template>
  <BaseMainSlot>
    <template v-slot:zhactbar>
      <selectlist @nowselectbutton="nowselectbutton" />
      <el-button class="selectAlls" type="text" @click="selectAll">
        全选
      </el-button>
      <el-button class="selectAllsd" type="text" @click="selectAlld">
        选择所有可查看功能
      </el-button>
      <el-button class="cancelSelectAlls" type="text" @click="cancelSelectAlls">
        取消全选
      </el-button>
      <ActionBar :has-add="false" :has-del="false" :has-edit="false" :has-cancel="false" :has-save="false"
        :save-active="saveActive" :has-saves="true" @save="save" />
    </template>
    <template v-slot:content>
      <el-tree ref="tree" :props="treerule" :data="treeData" show-checkbox node-key="functionNo" accordion
        :default-checked-keys="defaultchecklist" :check-strictly="true" @node-click="handleEdit"
        @check="handleSionChange" @check-change="handleSelectionChange" />
      <!-- :check-strictly="true"严格模式 -->
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components_yy/ActionBar/index.vue";
import BaseMainSlot from "@/components_yy/BaseMainSlot/kong.vue"
import { mymixin } from "@/utils/mixins"
// import zhrequest from "@/api/axios";
import selectlist from "./selectlist.vue"
import Axios from 'axios';

export default {
  components: {
    BaseMainSlot, ActionBar,
    selectlist
  },
  mixins: [mymixin],
  props: {
    username: {
      type: String,
      default: ''
    },
    userstu: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      treerule: {
        children: "childList",
        label: "functionName"
      },
      treeData: [],
      defaultchecklist: [],
      functionNos: [],
      treeDatas: [],
      treeDatad: [],
      userRouteMapperId: null,
      saveActive: false,
      cancelActive: false
    }
  },
  watch: {
    id() {
      this.getfuncauth()
    },
    userstu: {
      handler(Val) {
        if (Val === 'add') {
          this.save()
        }
      }
    }
  },
  mounted() {
    // this.getdatamet()
  },
  methods: {
    nowselectbutton(e) {
      this.virtualSystemNo = e.virtualSystemNo
      this.getdatamet(e)
    },
    getdatamet(e) {
      // let menuurlone
      // let params = {}
      // let orgid = getToken("organizationNo")
      // menuurlone = "v3/authority/v1/function/getSystemFunction"
      // zhrequest.get(menuurlone).then(
      //   res => {
      //     this.treeData = res.data || []
      //     this.getfuncauth()
      //   })
      let menuurlone = this.$baseurl.webServiceUrl + "v3/authority/v1/function/getSystemFunction"
      Axios({
        method: 'get',
        url: menuurlone,
        headers: {
          accessToken: sessionStorage.token,
          databaseName: sessionStorage.databaseName,
          organizationList: sessionStorage.organizationList,
          organizationNo: sessionStorage.organizationNo,
          virtualSystemNo: e.virtualSystemNo,
          lesseeNo: sessionStorage.lesseeNo
        }
      }).then(res => {
        this.treeData = res.data.data || []
        // console.log(res.data)
        // this.treeData.forEach(item => {
        //   item.metaName = item.meta.name
        //   this.$set(item, "metaName", item['meta']['title'])
        //   if (item.children) {
        //     item.children.forEach(itemTwo => {
        //       // itemTwo.metaName = itemTwo.meta.name
        //       this.$set(itemTwo, "metaName", itemTwo['meta']['title'])
        //     })
        //   }
        // })
        // console.log(this.treeData)
        this.getfuncauth(e)
        this.treeDatas = []
        this.treeDatad = []
        // console.log(this.treeDatas)
        this.gettreeList([...this.treeData])
        this.gettreeListd([...this.treeData])
      })
    },
    gettreeList(e) {
      let list = JSON.parse(JSON.stringify(e))
      for (let i = 0; list.length > i; i++) {
        this.treeDatas.push(list[i])
        if (list[i].childList && list[i].childList.length > 0) {
          this.gettreeList([...list[i].childList])
          delete list[i].childList
        }
      }
      // console.log(this.treeDatas)
    },
    gettreeListd(e) {
      let list = JSON.parse(JSON.stringify(e))
      for (let i = 0; list.length > i; i++) {
        this.treeDatad.push(list[i])
        if (list[i].level === 1) {
          if (list[i].childList && list[i].childList.length > 0) {
            this.gettreeListd([...list[i].childList])
            delete list[i].childList
          }
        }
      }
      // console.log(this.treeDatas)
    },
    // 获取所拥有的权限
    getfuncauth(e) {
      this.defaultchecklist = []
      let menuurlone = this.$baseurl.webServiceUrl + `v3/authority/v1/function/getOthers?username=${this.username}`
      // console.log(this.userid)
      Axios({
        method: 'get',
        url: menuurlone,
        headers: {
          accessToken: sessionStorage.token,
          databaseName: sessionStorage.databaseName,
          organizationList: sessionStorage.organizationList,
          organizationNo: sessionStorage.organizationNo,
          virtualSystemNo: e.virtualSystemNo,
          lesseeNo: sessionStorage.lesseeNo
        }
      }).then(res => {
        let PermissionList = res.data.data
        // console.log(PermissionList)
        let that = this
        that.$nextTick(
          () => {
            that.$refs.tree.setCheckedNodes([])
          }
        )
        PermissionList.forEach(item => {
          that.$nextTick(
            () => {
              // 设置某个节点
              that.$refs.tree.setChecked(item.functionNo, true)
            }
          )
        });
        // this.checklist = nowcheck
        if (res.data) {
          this.userRouteMapperId = '007'
        }
      })
      this.defaultchecklist = []
      // console.log(this.userid)
      // userManage.getfuncauth(this.username).then(res => {
      //   let PermissionList = res.data
      //   // console.log(PermissionList)
      //   let that = this
      //   that.$nextTick(
      //     () => {
      //       that.$refs.tree.setCheckedNodes([])
      //     }
      //   )
      //   PermissionList.forEach(item => {
      //     that.$nextTick(
      //       () => {
      //       // 设置某个节点
      //         that.$refs.tree.setChecked(item.functionNo, true)
      //       }
      //     )
      //   });
      //   // this.checklist = nowcheck
      //   if (res.data) {
      //     this.userRouteMapperId = '007'
      //   }
      // })
    },
    selectAll() {
      // this.flag = true;
      let that = this
      that.$nextTick(
        () => {
          this.$refs.tree.setCheckedNodes(this.treeDatas);
        })
      this.handleSionChange()
    },
    selectAlld() {
      // this.flag = true;
      let that = this
      that.$nextTick(
        () => {
          this.$refs.tree.setCheckedNodes(this.treeDatad);
        })
      this.handleSionChange()
    },
    cancelSelectAlls() {
      let that = this
      that.$nextTick(
        () => {
          that.$refs.tree.setCheckedNodes([])
        }
      )
    },
    handleEdit(row) {
      // console.log(row)
    },
    handleSionChange() {
      this.saveActive = true
      this.cancelActive = true
    },
    handleSelectionChange() {
      let list = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys());
      // console.log(list)
      this.functionNos = list
      // console.log(list)
      // if (this.handleSelectionChange) {
      // }
    },
    // 取消
    cancel() {
      this.canInput = false;
      this.addActive = false;
      this.delActive = false;
      this.saveActive = false;
      this.cancelActive = false;
      this.editActive = false;
      // let that = this
      // this.getfuncauth()
      // that.$nextTick(
      //   () => {
      //     that.$refs.tree.setCheckedNodes([])
      //   }
      // )
    },
    save() {
      // let par = {
      //   username: this.username,
      //   functionNos: this.functionNos
      // }
      let menuurlone = this.$baseurl.webServiceUrl + `v3/authority/v1/function/bindUser`
      // console.log(this.userid)
      Axios({
        method: 'post',
        url: menuurlone,
        headers: {
          accessToken: sessionStorage.token,
          databaseName: sessionStorage.databaseName,
          organizationList: sessionStorage.organizationList,
          organizationNo: sessionStorage.organizationNo,
          virtualSystemNo: this.virtualSystemNo,
          lesseeNo: sessionStorage.lesseeNo
        },
        data: `username=${this.username}&functionNOS=${this.functionNos}`
      }).then(res => {
        if (res.data.code === 1) {
          this.$message.success(res.data.msg || "修改成功！");
          // this.getfuncauth()
          this.$emit('roles', '')
          this.cancel()
        } else {
          this.$message.error(res.data.msg || "修改失败！");
        }
      })
      // userManage.addfuncauth(`username=${this.username}&functionNOS=${this.functionNos}`).then(res => {
      //   if (res.code === 1) {
      //     this.$message.success(res.msg || "修改成功！");
      //     // this.getfuncauth()
      //     this.$emit('users', '')
      //     this.cancel()
      //   } else {
      //     this.$message.error(res.msg || "修改失败！");
      //   }
      // })
      // console.log("设置权限")
    }
  }
}
</script>
<style lang="scss" scoped>
@import "~@/styles/variables.scss";

.tree {
  width: 100%;
  height: 100%;
  padding-left: 10px;
  padding-right: 30px;
}

::v-deep .el-tree {
  height: 100%;
  width: 100%;

  .el-tree-node {
    margin: 0;
    // margin-bottom: 10px;
  }
}

::v-deep .common-layout {
  padding: 0 !important;

  // height: calc(100% - 5px) !important;
  .zhcontent {
    height: 100% !important;
    margin: 0 !important;
  }
}

.selectAlls {
  position: absolute;
  height: 54px;
  width: 100px;
}

.selectAllsd {
  position: absolute;
  height: 54px;
  width: 100px;
  margin-left: 100px;
}

.cancelSelectAlls {
  position: absolute;
  height: 54px;
  width: 100px;
  margin-left: 250px;
}
</style>
